package com.woniu.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.woniu.been.entity.CourseCategories;
import com.woniu.been.entity.CourseChapters;
import com.woniu.been.entity.Courses;
import com.woniu.service.CourseCategoriesService;
import com.woniu.service.CourseChaptersService;
import com.woniu.service.CoursesService;
import com.woniu.utils.Result;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/course-hierarchy")
@CrossOrigin(origins = {"http://localhost:5174", "http://localhost:5173"}, allowCredentials = "true")
public class CourseHierarchyController {

    @Autowired
    private CourseCategoriesService courseCategoriesService;

    @Autowired
    private CourseChaptersService courseChaptersService;

    @Autowired
    private CoursesService coursesService;

    /**
     * 获取所有课程大类（parent_category_id为null的数据）
     * URL: /api/course-hierarchy/categories
     */
    @GetMapping("/categories")
    public Result<List<CourseCategories>> getMainCategories() {
        try {
            log.info("开始获取课程大类列表");
            List<CourseCategories> categories = courseCategoriesService.getAllTopLevelCategories();
            log.info("成功获取课程大类列表: {}", categories);
            return Result.success(categories);
        } catch (Exception e) {
            log.error("获取课程大类失败", e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 根据课程大类ID获取课程小类
     * URL: /api/course-hierarchy/categories/{categoryId}/subcategories
     */
    @GetMapping("/categories/{categoryId}/subcategories")
    public Result<List<CourseCategories>> getSubCategories(@PathVariable Integer categoryId) {
        try {
            log.info("开始获取课程小类列表, categoryId: {}", categoryId);
            List<CourseCategories> subCategories = courseCategoriesService.getSubCategoriesByParentId(categoryId);
            log.info("成功获取课程小类列表: {}", subCategories);
            return Result.success(subCategories);
        } catch (Exception e) {
            log.error("获取课程小类失败, categoryId: {}", categoryId, e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 根据课程小类ID获取章节列表
     * URL: /api/course-hierarchy/subcategories/{categoryId}/chapters
     */
    @GetMapping("/subcategories/{categoryId}/chapters")
    public Result<List<CourseChapters>> getChaptersBySubCategory(@PathVariable Integer categoryId) {
        try {
            log.info("开始获取章节列表, categoryId: {}", categoryId);
            List<CourseChapters> chapters = courseChaptersService.getChaptersBySubCategoryId(categoryId);
            log.info("成功获取章节列表: {}", chapters);
            return Result.success(chapters);
        } catch (Exception e) {
            log.error("获取章节列表失败, categoryId: {}", categoryId, e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 根据章节ID获取具体课程列表
     * URL: /api/course-hierarchy/chapters/{chapterId}/courses
     */
    @GetMapping("/chapters/{chapterId}/courses")
    public Result<List<Courses>> getCoursesByChapter(@PathVariable Integer chapterId) {
        try {
            log.info("开始获取具体课程列表, chapterId: {}", chapterId);
            List<Courses> courses = coursesService.getCoursesByChapterId(chapterId);
            log.info("成功获取具体课程列表: {}", courses);
            return Result.success(courses);
        } catch (Exception e) {
            log.error("获取具体课程列表失败, chapterId: {}", chapterId, e);
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 根据课程大类名称获取ID
     * URL: /api/course-hierarchy/categories/id-by-name/{categoryName}
     */
    @GetMapping("/categories/id-by-name/{categoryName}")
    public Result<Integer> getCategoryIdByName(@PathVariable String categoryName) {
        try {
            Integer id = courseCategoriesService.findCategoryIdByName(categoryName);
            if (id == null) {
                return Result.fail("未找到该课程大类");
            }
            return Result.success(id);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 根据课程小类名称获取ID
     * URL: /api/course-hierarchy/subcategories/id-by-name/{subCategoryName}
     */
    @GetMapping("/subcategories/id-by-name/{subCategoryName}")
    public Result<Integer> getSubCategoryIdByName(@PathVariable String subCategoryName) {
        try {
            Integer id = courseCategoriesService.findCategoryIdByName(subCategoryName);
            if (id == null) {
                return Result.fail("未找到该课程小类");
            }
            return Result.success(id);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 根据章节名称获取ID
     * URL: /api/course-hierarchy/chapters/id-by-name/{chapterName}
     */
    @GetMapping("/chapters/id-by-name/{chapterName}")
    public Result<Integer> getChapterIdByName(@PathVariable String chapterName) {
        try {
            Integer id = courseChaptersService.findChapterIdByName(chapterName);
            if (id == null) {
                return Result.fail("未找到该章节");
            }
            return Result.success(id);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 删除课程小类
     * URL: /api/course-hierarchy/subcategories/{id}
     * @param id 课程小类ID
     * @return 删除结果
     */
    @DeleteMapping("/subcategories/{id}")
    public Result<?> deleteSubCategory(@PathVariable Integer id) {
        try {
            log.info("开始删除课程小类, id: {}", id);
            courseCategoriesService.deleteCategory(id);
            log.info("成功删除课程小类, id: {}", id);
            return Result.success("课程小类删除成功");
        } catch (Exception e) {
            log.error("删除课程小类失败, id: {}", id, e);
            return Result.fail("删除课程小类失败: " + e.getMessage());
        }
    }

    /**
     * 删除章节
     * URL: /api/course-hierarchy/chapters/{id}
     * @param id 章节ID
     * @return 删除结果
     */
    @DeleteMapping("/chapters/{id}")
    public Result<?> deleteChapter(@PathVariable Integer id) {
        try {
            log.info("开始删除章节, id: {}", id);
            courseChaptersService.deleteChapter(id);
            log.info("成功删除章节, id: {}", id);
            return Result.success("章节删除成功");
        } catch (Exception e) {
            log.error("删除章节失败, id: {}", id, e);
            return Result.fail("删除章节失败: " + e.getMessage());
        }
    }

    /**
     * 删除具体课程
     * URL: /api/course-hierarchy/courses/{id}
     * @param id 具体课程ID
     * @return 删除结果
     */
    @DeleteMapping("/courses/{id}")
    public Result<?> deleteCourse(@PathVariable Long id) {
        try {
            log.info("开始删除具体课程, id: {}", id);
            coursesService.deleteCourse(id);
            log.info("成功删除具体课程, id: {}", id);
            return Result.success("具体课程删除成功");
        } catch (Exception e) {
            log.error("删除具体课程失败, id: {}", id, e);
            return Result.fail("删除具体课程失败: " + e.getMessage());
        }
    }

    /**
     * 新增课程小类
     * URL: /api/course-hierarchy/categories/{categoryId}/subcategories
     * @param categoryId 课程大类ID
     * @param subCategory 课程小类信息
     * @return 新增结果
     */
    @PostMapping("/categories/{categoryId}/subcategories")
    public Result<?> addSubCategory(@PathVariable Integer categoryId, @RequestBody CourseCategories subCategory) {
        try {
            log.info("开始新增课程小类, categoryId: {}, subCategory: {}", categoryId, subCategory);
            subCategory.setParentCategoryId(categoryId);
            courseCategoriesService.addCategory(subCategory);
            log.info("成功新增课程小类");
            return Result.success("课程小类新增成功");
        } catch (Exception e) {
            log.error("新增课程小类失败, categoryId: {}", categoryId, e);
            return Result.fail("新增课程小类失败: " + e.getMessage());
        }
    }

    /**
     * 编辑课程小类
     * URL: /api/course-hierarchy/subcategories/{id}
     * @param id 课程小类ID
     * @param subCategory 课程小类信息
     * @return 编辑结果
     */
    @PutMapping("/subcategories/{id}")
    public Result<?> updateSubCategory(@PathVariable Integer id, @RequestBody CourseCategories subCategory) {
        try {
            log.info("开始编辑课程小类, id: {}, subCategory: {}", id, subCategory);
            subCategory.setCategoryId(id);
            courseCategoriesService.updateCategory(subCategory);
            log.info("成功编辑课程小类");
            return Result.success("课程小类编辑成功");
        } catch (Exception e) {
            log.error("编辑课程小类失败, id: {}", id, e);
            return Result.fail("编辑课程小类失败: " + e.getMessage());
        }
    }

    /**
     * 新增章节
     * URL: /api/course-hierarchy/subcategories/{categoryId}/chapters
     * @param categoryId 课程小类ID
     * @param chapter 章节信息
     * @return 新增结果
     */
    @PostMapping("/subcategories/{categoryId}/chapters")
    public Result<?> addChapter(@PathVariable Integer categoryId, @RequestBody CourseChapters chapter) {
        try {
            log.info("开始新增章节, categoryId: {}, chapter: {}", categoryId, chapter);
            courseChaptersService.addChapter(chapter, categoryId);
            log.info("成功新增章节");
            return Result.success("章节新增成功");
        } catch (Exception e) {
            log.error("新增章节失败, categoryId: {}", categoryId, e);
            return Result.fail("新增章节失败: " + e.getMessage());
        }
    }

    /**
     * 编辑章节
     * URL: /api/course-hierarchy/chapters/{id}
     * @param id 章节ID
     * @param chapter 章节信息
     * @return 编辑结果
     */
    @PutMapping("/chapters/{id}")
    public Result<?> updateChapter(@PathVariable Integer id, @RequestBody CourseChapters chapter) {
        try {
            log.info("开始编辑章节, id: {}, chapter: {}", id, chapter);
            chapter.setChapterId(id);
            courseChaptersService.updateChapter(chapter);
            log.info("成功编辑章节");
            return Result.success("章节编辑成功");
        } catch (Exception e) {
            log.error("编辑章节失败, id: {}", id, e);
            return Result.fail("编辑章节失败: " + e.getMessage());
        }
    }

    /**
     * 新增具体课程
     * URL: /api/course-hierarchy/chapters/{chapterId}/courses
     * @param chapterId 章节ID
     * @param course 具体课程信息
     * @return 新增结果
     */
    @PostMapping("/chapters/{chapterId}/courses")
    public Result<?> addCourse(@PathVariable Integer chapterId, @RequestBody Courses course) {
        try {
            log.info("开始新增具体课程, chapterId: {}, course: {}", chapterId, course);
            coursesService.addCourse(course, chapterId);
            log.info("成功新增具体课程");
            return Result.success("具体课程新增成功");
        } catch (Exception e) {
            log.error("新增具体课程失败, chapterId: {}", chapterId, e);
            return Result.fail("新增具体课程失败: " + e.getMessage());
        }
    }

    /**
     * 编辑具体课程
     * URL: /api/course-hierarchy/courses/{id}
     * @param id 具体课程ID
     * @param course 具体课程信息
     * @return 编辑结果
     */
    @PutMapping("/courses/{id}")
    public Result<?> updateCourse(@PathVariable Long id, @RequestBody Courses course) {
        try {
            log.info("开始编辑具体课程, id: {}, course: {}", id, course);
            course.setCourseId(id);
            coursesService.updateCourse(course);
            log.info("成功编辑具体课程");
            return Result.success("具体课程编辑成功");
        } catch (Exception e) {
            log.error("编辑具体课程失败, id: {}", id, e);
            return Result.fail("编辑具体课程失败: " + e.getMessage());
        }
    }

    /**
     * 测试方法：检查数据库中的数据
     * URL: /api/course-hierarchy/test-data
     */
    @GetMapping("/test-data")
    public Result<Map<String, Object>> testData() {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 获取所有课程大类
            List<CourseCategories> mainCategories = courseCategoriesService.getAllTopLevelCategories();
            result.put("mainCategories", mainCategories);
            result.put("mainCategoriesCount", mainCategories.size());
            
            // 获取第一个课程大类的小类
            if (!mainCategories.isEmpty()) {
                Integer firstCategoryId = mainCategories.get(0).getCategoryId();
                result.put("firstCategoryId", firstCategoryId);
                
                List<CourseCategories> subCategories = courseCategoriesService.getSubCategoriesByParentId(firstCategoryId);
                result.put("subCategories", subCategories);
                result.put("subCategoriesCount", subCategories.size());
                
                // 获取第一个小类的章节
                if (!subCategories.isEmpty()) {
                    Integer firstSubCategoryId = subCategories.get(0).getCategoryId();
                    result.put("firstSubCategoryId", firstSubCategoryId);
                    
                    List<CourseChapters> chapters = courseChaptersService.getChaptersBySubCategoryId(firstSubCategoryId);
                    result.put("chapters", chapters);
                    result.put("chaptersCount", chapters.size());
                    
                    // 获取第一个章节的具体课程
                    if (!chapters.isEmpty()) {
                        Integer firstChapterId = chapters.get(0).getChapterId();
                        result.put("firstChapterId", firstChapterId);
                        
                        List<Courses> courses = coursesService.getCoursesByChapterId(firstChapterId);
                        result.put("courses", courses);
                        result.put("coursesCount", courses.size());
                    }
                }
            }
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("测试数据查询失败", e);
            return Result.fail("测试数据查询失败: " + e.getMessage());
        }
    }
}